//
//  SaPublicWay.m
//  saas
//
//  Created by fangyibao on 2020/7/27.
//  Copyright © 2020 fangmao. All rights reserved.
//

#import "SaPublicWay.h"
//#import "WXApi.h"
//#import "WXApiObject.h"
#import "SaTime.h"


@implementation SaPublicWay

//转化为千分位格式,例如 :33369080 输出：33,369,080
+(NSString*)changeNumberFormatter:(NSString*)str{
   NSString *numString = [NSString stringWithFormat:@"%@",str];
   NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
   NSNumber *number = [formatter numberFromString:numString];
   formatter.numberStyle = kCFNumberFormatterDecimalStyle;
   NSString *string = [formatter stringFromNumber:number];
   NSLog(@"numberFormatter == %@",string);
   if(IsStrEmpty(string)) {
   return str;
   }
   return string;
}

+(UIImage*)image:(UIImage *)image scaleToSize:(CGSize)size{
    
    // 得到图片上下文，指定绘制范围
    UIGraphicsBeginImageContext(size);
    
    // 将图片按照指定大小绘制
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前图片上下文中导出图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 当前图片上下文出栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}


+(UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect{
    
    //将UIImage转换成CGImageRef
    CGImageRef sourceImageRef = [image CGImage];
    
    //按照给定的矩形区域进行剪裁
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    
    //将CGImageRef转换成UIImage
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    //返回剪裁后的图片
    return newImage;
}


+(UIImage *)cropSquareImage:(UIImage *)image{
    CGImageRef sourceImageRef = [image CGImage];//将UIImage转换成CGImageRef
    
    CGFloat _imageWidth = image.size.width * image.scale;
    CGFloat _imageHeight = image.size.height * image.scale;
    CGFloat _width = _imageWidth > _imageHeight ? _imageHeight : _imageWidth;
    CGFloat _offsetX = (_imageWidth - _width) / 2;
    CGFloat _offsetY = (_imageHeight - _width) / 2;
    
    CGRect rect = CGRectMake(_offsetX, _offsetY, _width, _width);
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);//按照给定的矩形区域进行剪裁
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    return newImage;
}


+(NSString *)InputContentType:(NSString *)type{
    NSString * outStr;
    if ([type isEqualToString:@"1"]) {
        outStr = @"挑房";
    }else if ([type isEqualToString:@"2"]){
        outStr = @"楼盘";
    }else if ([type isEqualToString:@"3"]){
        outStr = @"店铺";
    }else if([type isEqualToString:@"4"]){
        outStr = @"活动";
    }else if([type isEqualToString:@"5"]){
        outStr = @"活动";
    }else if([type isEqualToString:@"6"]){
        outStr = @"委托找房";
    }else if([type isEqualToString:@"7"]){
        outStr = @"此房源";
    }
    
    return outStr;
    
}

+(NSMutableDictionary *)inputOldHouseSortData:(NSInteger)index{
    NSMutableDictionary * dic = @{}.mutableCopy;
    if (index == 0) {
        [dic setValue:@"" forKey:@"orderType"];
        [dic setValue:@"" forKey:@"orderField"];
    }else if (index == 1){// 最近挂牌
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"8" forKey:@"orderField"];
    }else if (index == 2){
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"4" forKey:@"orderField"];
    }else if (index == 3){
        [dic setValue:@"asc" forKey:@"orderType"];
        [dic setValue:@"4" forKey:@"orderField"];
    }else if (index == 4){
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"3" forKey:@"orderField"];
    }else if (index == 5){
        [dic setValue:@"asc" forKey:@"orderType"];
        [dic setValue:@"12" forKey:@"orderField"];
    }
    return dic;
}

+(NSMutableDictionary *)inputLeaseSortData:(NSInteger)index{
    NSMutableDictionary * dic = @{}.mutableCopy;
    if (index == 0) {
        [dic setValue:@"" forKey:@"orderType"];
        [dic setValue:@"" forKey:@"orderField"];
    }else if (index == 1){// 最近挂牌
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"8" forKey:@"orderField"];
    }else if (index == 2){
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"11" forKey:@"orderField"];
    }else if (index == 3){
        [dic setValue:@"asc" forKey:@"orderType"];
        [dic setValue:@"11" forKey:@"orderField"];
    }else if (index == 4){
        [dic setValue:@"desc" forKey:@"orderType"];
        [dic setValue:@"3" forKey:@"orderField"];
    }else if (index == 5){
        [dic setValue:@"asc" forKey:@"orderType"];
        [dic setValue:@"3" forKey:@"orderField"];
    }
    return dic;
}




// 打开微信小程序
//+ (BOOL)openWechatMinPraogramWithUserName:(NSString *)userName path:(NSString *)path miniProgramType:(WXMiniProgramType)miniProgramType{
////    BOOL isRegi = [WXApi registerApp:kWechatAPP_ID];
//    BOOL isRegi = [WXApi registerApp:@"" universalLink:@""];
//    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
//    launchMiniProgramReq.userName = userName;  //拉起的小程序的username
//    launchMiniProgramReq.path = path;    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
//    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeTest; //拉起小程序的类型
//    BOOL isSendStatus = [WXApi sendReq:launchMiniProgramReq];
//    return isSendStatus;
//}


+ (void)copyWeixinByWechatNickName:(NSString *)nickname{
    
    UIPasteboard *pad = [UIPasteboard generalPasteboard];
    pad.string = nickname;
    if (pad == nil) {
        [SaProgressHUD showText:@"复制失败"];
        return;
    }else{
        [SaProgressHUD showText:@"微信号已复制到剪贴板"];
//        if ([WXApi isWXAppInstalled]) {
//            // 定时器  延迟秒在出现 进入微信应用
//            double delayInSeconds = 3.0;
//             dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//
//                NSString * str = [NSString stringWithFormat:@"weixin://%@",@"https://help.wechat.com/app/"];
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
//
//            });
//
//        }else{
//            [SaProgressHUD showText:@"用户未安装微信"];
//            return;
//        }
        
    }
    
    
}

+(NSAttributedString *)generateAttrbuteString:(NSString *)first Color:(UIColor *)color Font:(UIFont *)font count:(NSString *)count{
    NSMutableParagraphStyle *s = [NSMutableParagraphStyle new];
    s.lineSpacing = ALIGN_HEIGHT_PT(10);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@", first, count]];
    NSMutableParagraphStyle *ps = [NSMutableParagraphStyle new];
    ps.lineSpacing = ALIGN_HEIGHT_PT(10);
    [attr addAttributes:@{NSForegroundColorAttributeName:color, NSFontAttributeName:font} range:NSMakeRange(attr.length-count.length, count.length)];
    [attr addAttribute:NSParagraphStyleAttributeName value:s range:NSMakeRange(0, attr.length)];
    
    return attr;
}


+(NSString *)inputMonthStr{
    // 获取代表公历的NSCalendar对象
      NSCalendar *gregorian = [[NSCalendar alloc]
       initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
      // 获取当前日期
      NSDate* dt = [NSDate date];
      // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
      unsigned unitFlags = NSCalendarUnitYear |
       NSCalendarUnitMonth |  NSCalendarUnitDay |
       NSCalendarUnitHour |  NSCalendarUnitMinute |
       NSCalendarUnitSecond | NSCalendarUnitWeekday;
      // 获取不同时间字段的信息
      NSDateComponents* comp = [gregorian components: unitFlags
       fromDate:dt];
    NSString * str = [NSString stringWithFormat:@"%@月%@日",@(comp.month),@(comp.day)];
    
    return str;
    
    
      // 获取各时间字段的数值
//      NSLog(@"现在是%ld年" , comp.year);
//      NSLog(@"现在是%ld月 " , comp.month);
//      NSLog(@"现在是%ld日" , comp.day);
//      NSLog(@"现在是%ld时" , comp.hour);
//      NSLog(@"现在是%ld分" , comp.minute);
//      NSLog(@"现在是%ld秒" , comp.second);
//      NSLog(@"现在是星期%ld" , comp.weekday);
      // 再次创建一个NSDateComponents对象
//      NSDateComponents* comp2 = [[NSDateComponents alloc]
//       init];
//      // 设置各时间字段的数值
//      comp2.year = 2013;
//      comp2.month = 4;
//      comp2.day = 5;
//      comp2.hour = 18;
//      comp2.minute = 34;
//      // 通过NSDateComponents所包含的时间字段的数值来恢复NSDate对象
//      NSDate *date = [gregorian dateFromComponents:comp2];
//      NSLog(@"获取的日期为：%@" , date);
}

#pragma mark -- 将view生成图片
+(void)transformViewBecomeImg:(UIView *)view{
//    CGSize size = CGSizeMake(ALIGN_WIDTH_PT(1080), ALIGN_HEIGHT_PT(1920));
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES,0.0);
     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
//     NSData *imageData = UIImageJPEGRepresentation(image,1.0f);
    NSData * imageData = UIImagePNGRepresentation(image);
    // NSData转化为图片
    UIImage * img = [UIImage imageWithData:imageData];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(p_w_picpathSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

- (void)p_w_picpathSavedToPhotosAlbum:(UIImage *)p_w_picpath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"成功";
    if (!error) {
        [SaProgressHUD showText:@"保存成功"];
    }else
    {
        message = [error description];
        [SaProgressHUD showText:message];
    }
}

#pragma mark -- 生成分享图片
+(UIImage *)shareImageByView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     NSData *imageData = UIImageJPEGRepresentation(image,1.0f);
    // NSData转化为图片
    UIImage * img = [UIImage imageWithData:imageData];
    return img;
}


//富文本 显示不同的颜色
+(NSMutableAttributedString *)getPriceAttribute:(NSString *)string length:(NSInteger)lenght Font:(UIFont *)font Color:(UIColor *)color{
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string];
    //目的是想改变 ‘:’前面的字体的属性，所以找到目标的range
//    NSRange range = [string rangeOfString:@":"];
    NSRange pointRange = NSMakeRange(0, lenght);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSFontAttributeName] = font;
    dic[NSForegroundColorAttributeName] = color;
    [attribut addAttributes:dic range:pointRange];
    return attribut;
}


+(NSString *)getNowTimeTimestamp3{

    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];

    return timeSp;
}


+(NSString *)inputDateStr:(NSString *)str{
    
    //时间
    NSString *createdTimeStr = str;
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr];
    //得到与当前时间差
    NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
     result = [NSString stringWithFormat:@"刚刚"];
    }else if((temp = timeInterval/60) < 60){
     result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }else if((temp = timeInterval/3600) >= 1 && (temp = timeInterval/3600) <24){
     result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
//    else if ((temp = timeInterval/3600) >= 24 && (temp = timeInterval/3600) < 48){
//     result = [NSString stringWithFormat:@"昨天"];
//    }else if ((temp = timeInterval/3600) >= 48 && (temp = timeInterval/3600) < 72){
//     result = [NSString stringWithFormat:@"前天"];
//    }
    else{
        
    NSString * dateS = [SaTime transFormTime:str];
    
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    result = [dateS substringWithRange:NSMakeRange(5, 6)]; // 非今天
    
    }

    return result;
}


+(UIImage *)addWatermarketWithOriginImage:(UIImage *)originImage WaterText:(NSString *)waterText{
    
    //原始image的宽高
    CGFloat viewWidth = originImage.size.width;
    CGFloat viewHeight = originImage.size.height;
    
    UIGraphicsBeginImageContextWithOptions(originImage.size, NO, 0);
    // 绘制图片
    [originImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight)];
    // 添加水印
    if (waterText.length > 0) {
        CGFloat horizontalSpace = 50;// 水平间隔
        CGFloat vertivalSpace = 100; // 竖直间隔
        NSDictionary *attributedDic =@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor],NSBackgroundColorAttributeName:[UIColor clearColor]};
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:waterText attributes:attributedDic];
        //绘制文字的宽高
        CGFloat strWidth = attrStr.size.width;
        CGFloat strHeight = attrStr.size.height;
        // 开始旋转上下文矩阵，绘制水印文字
        CGContextRef context = UIGraphicsGetCurrentContext();
        //将绘制原点（0，0）调整到源image的中心
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(viewWidth/2, viewHeight/2));
        //以绘制原点为中心旋转  (M_PI_2 / 3 ) <45>角度
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(-(M_PI_2 / 3)));
    //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-viewWidth/2, -viewHeight/2));
        
        // 对角线
        CGFloat sqrtLength = sqrt(viewWidth*viewWidth + viewHeight*viewHeight);
        //计算需要绘制的列数和行数
        int horCount = sqrtLength / (strWidth + horizontalSpace) + 1;
        int verCount = sqrtLength / (strHeight + vertivalSpace) + 1;
        
        //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
        CGFloat orignX = -(sqrtLength-viewWidth)/2;
        CGFloat orignY = -(sqrtLength-viewHeight)/2;
        //在每列绘制时X坐标叠加
        CGFloat tempOrignX = orignX;
        //在每行绘制时Y坐标叠加
        CGFloat tempOrignY = orignY;
        for (int i = 0; i < horCount * verCount; i++) {
            [waterText drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attributedDic];
            if (i % horCount == 0 && i != 0) {
                tempOrignX = orignX;
                tempOrignY += (strHeight + vertivalSpace);
            }else{
                tempOrignX += (strWidth + horizontalSpace);
            }
        }
    }
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}


+(NSString *)getDealNumwithstring:(NSString *)string{
    NSDecimalNumber *numberA = [NSDecimalNumber decimalNumberWithString:string];
    NSDecimalNumber *numberB ;
    NSString *unitStr;
    if (string.length > 3 ) {
        numberB =  [NSDecimalNumber decimalNumberWithString:@"10000"];
        unitStr = @"万";
    }else{
        return string;
    }
    //NSDecimalNumberBehaviors对象的创建  参数 1.RoundingMode 一个取舍枚举值 2.scale 处理范围 3.raiseOnExactness  精确出现异常是否抛出原因 4.raiseOnOverflow  上溢出是否抛出原因  4.raiseOnUnderflow  下溢出是否抛出原因  5.raiseOnDivideByZero  除以0是否抛出原因。
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:1 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    
    /// 这里不仅包含Multiply还有加 减 乘。
    NSDecimalNumber *numResult = [numberA decimalNumberByDividingBy:numberB withBehavior:roundingBehavior];
    NSString *strResult = [NSString stringWithFormat:@"%@%@",[numResult stringValue],unitStr];
    return strResult;
}

+(NSString *)cellPhoneAddString:(NSString *)string{
    NSMutableString * mutableStr  = [[NSMutableString alloc]initWithString:string];
    [mutableStr insertString:@" " atIndex:3];
    [mutableStr insertString:@" " atIndex:string.length - 3];
    return mutableStr;
}



@end

